<template>
  <div>
    <div style="margin-bottom: 10px; display: flex; align-items: center">
      <el-button @click="changeType('huabi')" type="primary">画笔</el-button>
      <el-button @click="changeType('rect')" type="success">正方形</el-button>
      <el-button
        @click="changeType('arc')"
        type="warning"
        style="margin-right: 10px"
        >圆形</el-button
      >
      <div>颜色：</div>
      <el-color-picker v-model="color" />
      <el-button @click="clear">清空</el-button>
      <el-button @click="saveImg">保存</el-button>
    </div>
    <canvas
    id='canvas'
      ref="canvasEl"
      width="800"
      height="400"
      @mousedown="hanldeMousedown"
      @mousemove="hanldeMousemove"
      @mouseup="hanldeMouseup"
    >
    </canvas>
  </div>
</template>

<script lang='ts'>
import { ref } from '@vue/reactivity'
import { defineComponent, onMounted } from '@vue/runtime-core'
export default defineComponent({

  setup () {
    const canvasEl = ref<HTMLCanvasElement>(null)
    const canvasCtx = ref<CanvasRenderingContext2D>(null)
    const ctxType = ref<'pencil'|'arc'|'rect'>('pencil')
    const color = ref('#409EFF')
    const canDraw = ref(false)

    function changeType (type) {
      ctxType.value = type
    }
    function hanldeMousedown (e) {
      canDraw.value = true
      canvasCtx.value.beginPath()
      canvasCtx.value.strokeStyle = color.value
      canvasCtx.value.moveTo(e.offsetX, e.offsetY)
    }
    function hanldeMouseup () {
      canDraw.value = false
      canvasCtx.value.closePath()
    }
    function hanldeMousemove (e) {
      if (!canDraw.value) {
        return false
      }
      const x = e.offsetX
      const y = e.offsetY
      if (ctxType.value === 'pencil') {
        // canvasCtx.value.strokeStyle = color.value
        // canvasCtx.value.lineTo(x, y)
        // canvasCtx.value.stroke()

        drawPencil(x, y)
      }
    }
    function drawPencil (x, y) {
      canvasCtx.value.lineTo(x, y)
      canvasCtx.value.stroke()
      // canvasCtx.value.closePath()
    }
    function clear () {
      canvasCtx.value.clearRect(0, 0, 800, 400)
    }
    function saveImg () {
      const url = canvasEl.value.toDataURL()
      let a = document.createElement('a')
      a.href = url
      a.download = 'sunshine.png'
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      a = null
    }

    onMounted(() => {
      canvasCtx.value = canvasEl.value?.getContext('2d')
    })
    return {
      changeType,
      clear,
      saveImg,
      hanldeMousedown,
      hanldeMouseup,
      hanldeMousemove,
      color,
      canvasEl,
    }
  },

})
</script>

<style lang="less" scoped>
#canvas {
  border: 1px solid black;
}
</style>
